<?php
/*
 * [JINYUN!] (C)2001-2099 Jinyunweb.com
 * This is NOT a freeware, use is subject to license terms
 * $Id: 2017-12-13 03:39:35 apple $
*/
defined('BY_JYA') or exit('error');
$_RQ['op']=$_RQ['op']?$_RQ['op']:'step1';
$merchid=$_SESSION['onemerchid'];
$return['steps']=array(
	array('title'=>'结算消息','en_title'=>'Shareholders'),
	array('title'=>'创建结算单','en_title'=>'Team info'),
);
$setting=plugin('jy_merch')->plugin_setting('setting');
if($setting['tixian_timetype']==1 && $_RQ['op']=='step1' && !$_RQ['isto']){
	$_RQ['op']='step0';
}
if($_RQ['op']=='step0'){
	if($_RQ['id']){
		$merchid=intval($_RQ['id']);
		$_SESSION['onemerchid']=$merchid;
	}
	if($_RQ['postdata']){
		$postdata=get_postdata();
		if(!$postdata['year'] || !$postdata['month'] ){
			exi('请选择年份，月份！','error');
		}
		$year=intval(date('Y',time()));
		$month=intval(date('m',time()));
		if($year==$postdata['year'] && $postdata['month']>=$month){
			exi('不能选择本月及以后月份！','error');
		}
		if($setting['tixian_timeday'] && $year==$postdata['year'] && $postdata['month']==$month-1){
			$nowyuetime=mktime(0,0,0,date('m'),1,date('Y'));
			if($nowyuetime+24*3600*($setting['tixian_timeday']-1)>time()){
				exi('次月第'.$setting['tixian_timeday'].'天开始结算！','error');
			}
		}
		if($year==$postdata['year'] && $postdata['month']>=$month){
			exi('不能选择本月及以后月份！','error');
		}
		exi('','','/apply_add/step1/isto=1&year1='.$postdata['year'].'&month1='.$postdata['month']);
	}
	$year=intval(date('Y',time()));
	$return['year']=array('0'=>array('id'=>$year-9,'title'=>$year-9),'1'=>array('id'=>$year-8,'title'=>$year-8),'2'=>array('id'=>$year-7,'title'=>$year-7),'3'=>array('id'=>$year-6,'title'=>$year-6),'4'=>array('id'=>$year-5,'title'=>$year-5),'5'=>array('id'=>$year-4,'title'=>$year-4),'6'=>array('id'=>$year-3,'title'=>$year-3),'7'=>array('id'=>$year-2,'title'=>$year-2),'8'=>array('id'=>$year-1,'title'=>$year-1),'9'=>array('id'=>$year,'title'=>$year));
	$return['month']=array('0'=>array('id'=>1,'title'=>1),'1'=>array('id'=>2,'title'=>2),'2'=>array('id'=>3,'title'=>3),'3'=>array('id'=>4,'title'=>4),'4'=>array('id'=>5,'title'=>5),'5'=>array('id'=>6,'title'=>6),'6'=>array('id'=>7,'title'=>7),'7'=>array('id'=>8,'title'=>8),'8'=>array('id'=>9,'title'=>9),'9'=>array('id'=>10,'title'=>10),'10'=>array('id'=>11,'title'=>11),'11'=>array('id'=>12,'title'=>12));
	if($setting['tixian_timetype']==1){
		$tixian_timeday=$setting['tixian_timeday']?:1;
		$tixian_timetips='按月结算，请选择要结算的月份，次月第'.$tixian_timeday.'天可结算！';
	}else{
		$tixian_timetips='订单完成就后，随时可结算！';
	}
	$return['item']=$item;
	$htmls=array(
		'type'=>'edit',
		'edit'=>array(
			array('title'=>'[温馨提示]：每次最大提现1000个订单；如订单过多，需要分批结算；','type'=>'tip'),
			array('title'=>$tixian_timetips,'type'=>'title'),
			array('name'=>'year','title'=>'选择年份','type'=>'select','options'=>'year'),
			array('name'=>'month','title'=>'选择月份','type'=>'select','options'=>'month'),
		)
	);
	$return['htmls']=$htmls;
	$item['tixian_timetype']=$setting['tixian_timetype'];
	exi($return);
}
if($_RQ['op']=='step1' || $_RQ['op']=='edit'){
	if($_RQ['id']){
		$merchid=intval($_RQ['id']);
		$_SESSION['onemerchid']=$merchid;
	}
	$year=$_RQ['year1'];
	$month=$_RQ['month1'];
	$month=$month>9?$month:'0'.$month;
	$return['step']=1;
	$return['pay_types']=array('union'=>'银行卡');
	$wxapppay_types=array();
	foreach($return['pay_types'] as $key=>$title){
		$wxapppay_types[]=array('key'=>$key,'title'=>$title);
	}
	$return['wxapppay_types']=$wxapppay_types;
	$params=array('status'=>3,'uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'clearstatus'=>0);
	if(!$year && $setting['balance_day']){
	//结算天数
		$time=TIMESTAMP-intval($setting['balance_day'])*86400;
		$this->session('balance_time',$time);
		$params['finishtime <']=$time;
	}elseif($year){
		$starttime = strtotime($year.$month."01000000");
		$firstdaystr = date("Y-m-01", $starttime);
		$endtime = strtotime(date('Y-m-d 23:59:59', strtotime("$firstdaystr +1 month -1 day")));
		$params['createtime between']=array($starttime,$endtime);
	}
	$pindex = max(1, 1);
	$psize = 1000;
	$total='';
	$fields=array('id','mid','price','paytype','api_data','pay_id','createtime','peisong_id','dispatchprice','clearstatus','status','merchid','buytype','out_upfee','isdish');
	$ordergoods=pdo_getslice('jy_weishop_order',$params,array($pindex,$psize),$total,$fields);
	if($ordergoods){
			$user=array();
			$salsecount=count($ordergoods);
			$item['ordermoney']=0;
			$item['commission_money']=0;
			$item['allgoodsfee']=0;
			$sys_choufee=0;
			$item['peifee']=0;
			$item['out_upfee']=0;
			$item['orderids']=array();
			if($this->plugin_exists('jy_commission')){
				$jy_commission=1;
			}
			$item['pingfee']=0;
			$item['dafee']=0;
			$item['fuwufee']=0;
			$item['jieprice']=0;
			foreach($ordergoods as $k=>$v){
				//剔除商户独立支付的
				$payonemerchid=pdo_getcolumn('core_paylog',array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['pay_id']),'onemerchid');
				if(($v['paytype']=='wechat' || $v['paytype']=='credit') && $payonemerchid){
					pdo_update('jy_weishop_order',array('clearstatus'=>5),array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['id']));
				}
				$isclear=pdo_get('jy_weishop_order_goods',array('clearstatus >='=>1,'uniacid'=>$_SESSION['uniacid'],'orderid'=>$v['id']));
				if($isclear['id']){
					pdo_update('jy_weishop_order',array('clearstatus'=>$isclear['clearstatus']),array('uniacid'=>$_SESSION['uniacid'],'id'=>$v['id']));
					continue;
				}
				$status=$v['status'];
				$get_choufee=model('jy_merch/commission')->get_choufee($v,true,$merchid,1);
				$sys_choufee +=$get_choufee['commission_money'];
				if($jy_commission){
					$commission_money=model('jy_commission/commission')->get_orderfee($v['id']);
				}
				$item['ordermoney'] +=$v['price'];
				$item['out_upfee'] +=$v['out_upfee'];
				$item['commission_money'] +=$commission_money;
				$item['allgoodsfee'] +=$get_choufee['allgoodsfee'];
				$item['orderids'][]=$v['id'];
				if($v['peisong_id']){
					$sys_peiprice=pdo_getcolumn('jy_merch_order',array('uniacid'=>$_SESSION['uniacid'],'order_id'=>$v['id']),'sys_peiprice');
					$sys_peiprice=$sys_peiprice>0?$sys_peiprice:$v['dispatchprice'];
					$item['peifee'] +=$sys_peiprice;
				}
				$api_data=json_decode($v['api_data'],true);
				$item['pingfee'] +=$api_data['pingfee'];
				$item['dafee'] +=$api_data['dafee'];
				$v['jieprice']=$v['price']-$api_data['api_data']['pingfee']-$api_data['api_data']['dafee'];
				$item['jieprice'] +=$v['jieprice'];
			}
	}
	$item['year2']=$year;
	$item['month2']=$month;
	$item['koufee']=$item['allgoodsfee']+$item['peifee']+$item['out_upfee']-$item['ordermoney'];
	$params=array('status'=>1,'merchid'=>$merchid,'uniacid'=>$_SESSION['uniacid'],'clearstatus'=>0);
	if($time){
		$params['createtime <']=$time;
	}
	if($year){
		$params['createtime between']=array($starttime,$endtime);
		$item['endtime']=$endtime;
		$item['starttime']=$starttime;
	}else{
		$item['endtime']=$time?:TIMESTAMP;
	}
	$item['inpaymoney']=pdo_getsum('jy_merch_paylog',$params,'money');
	$item['inpaycount']=pdo_count('jy_merch_paylog',$params,'id');
	$allnum=$salsecount+$item['inpaycount'];
	if(!$allnum){
		//exi('没有可结算订单','error');
	}
	
	$item['salsecount']=$salsecount;
	$item['ordermoney']=intval($item['ordermoney']*100)/100;
	$item['realprice']=$item['ordermoney']+$item['inpaymoney'];
	$item['price']=$item['realprice']-$item['peifee'];
	if($setting['educt_commission']==1){
			$item['price']=$item['price']-$item['commission_money'];
			$item['educt_commission']=1;
	}
	$merch=pdo_get('jy_merch_user',array('uniacid'=>$_SESSION['uniacid'],'id'=>$merchid));
	$msetting=json_decode($merch['setting'],true);
	$payrate=$merch['payrate'];
	$item['bankcard']=$msetting['bankcard'];
	$item['realname']=$msetting['realname'];
	$item['cname']=$msetting['cname'];
	//获取计算的抽成
	$item['sys_choufee']=$sys_choufee;
	$item['realpricerate']=$item['price']-$item['sys_choufee'];
	//扣手续费
	$item['feerate']=intval($setting['feerate']*100)/100;
	$item['ratefee']=$item['realpricerate']*$item['feerate']/100;
	$item['finalprice']=$item['jieprice']-$item['sys_choufee'];
	$item['ratefee']=price($item['ratefee']);
	$item['price']=price($item['price']);
	$item['commission_money']=price($item['commission_money']);
	$item['sys_choufee']=price($item['sys_choufee']);
	$item['finalprice']=intval($item['finalprice']*100)/100;
	$item['allgoodsfee']=price($item['allgoodsfee']);
	$item['koufee']=price($item['koufee']);
	$item['pay_type']='union';
	if($setting['tixian_timetype']==1){
		$tixian_timeday=$setting['tixian_timeday']?:1;
		$tixian_timetips='按月结算，请选择要结算的月份，次月第'.$tixian_timeday.'天可结算！';
	}else{
		$tixian_timetips='订单完成就后，随时可结算！';
	}
	$item['tixian_timetype']=$setting['tixian_timetype'];
	$return['tixian_timetips']=$tixian_timetips;
	$return['item']=$item;
	$htmls=array(
		'type'=>'edit',
		'post'=>'step2',
		'edit'=>array(
					array('title'=>'[温馨提示]：每次最大提现1000个订单；如订单过多，需要分批结算；','type'=>'tip'),
					array('title'=>$tixian_timetips,'type'=>'title'),
					array('name'=>'year2','title'=>'结算年份','type'=>'copy','show'=>array('tixian_timetype'=>1)),
					array('name'=>'month2','title'=>'结算月份','type'=>'copy','show'=>array('tixian_timetype'=>1)),
					//array('name'=>'pay_type','title'=>'打款方式','type'=>'radio','options'=>'pay_types'),
					//array('type'=>'string','name'=>'realname','title'=>'真实姓名','help'=>'微信打款（满2000后必须提供真实姓名）'),
					//array('type'=>'string','name'=>'alipay','title'=>'支付宝帐号','show'=>array('pay_type'=>array('alipay'))),
					//array('type'=>'string','name'=>'alipay1','title'=>'确认支付宝帐号','show'=>array('pay_type'=>array('alipay'))),
					//array('type'=>'string','name'=>'bankcard','title'=>'收款银行账户','read'=>true,'show'=>array('pay_type'=>array('union'))),
					//array('type'=>'string','name'=>'realname','title'=>'收款账户名称','read'=>true,'show'=>array('pay_type'=>array('union'))),
					//array('name'=>'salsecount','title'=>'商品销量','type'=>'unitstring','unit'=>'单','read'=>true),
					array('name'=>'ordermoney','title'=>'订单实收','type'=>'unitstring','unit'=>'元','read'=>true),
					//array('name'=>'allgoodsfee','title'=>'订单金额','type'=>'unitstring','unit'=>'元','read'=>true),
					array('name'=>'pingfee','title'=>'平台服务费','type'=>'unitstring','unit'=>'元','read'=>true),
					array('name'=>'dafee','title'=>'达人佣金','type'=>'unitstring','unit'=>'元','read'=>true),
					array('name'=>'fuwufee','title'=>'服务商佣金','type'=>'unitstring','unit'=>'元','read'=>true),
					array('name'=>'jieprice','title'=>'商家结算金额','type'=>'unitstring','unit'=>'元','read'=>true),
					//array('name'=>'ratefee','title'=>'提现手续费','type'=>'unitstring','unit'=>'元','read'=>true),
					//array('name'=>'commission_money','title'=>'扣除佣金','type'=>'unitstring','unit'=>'元','read'=>true,'show'=>array('educt_commission'=>1),'help'=>'设置里面开启了扣除佣金，这次才会显示！【注意】：<red>只有存在上级或开启分销内购的订单</red>，并产生佣金时，才有效！'),
					array('name'=>'sys_choufee','title'=>'平台抽成','type'=>'unitstring','unit'=>'元','read'=>true,'help'=>'不同类型商户抽成比例不一样！'),
					array('name'=>'finalprice','title'=>'实际最终结算金额','type'=>'unitstring','unit'=>'元','read'=>true),
					//array('name'=>'jifen','title'=>'赠送积分','type'=>'unitstring','unit'=>'个','read'=>true),
					array('type'=>'text','title'=>'申请事由','name'=>'content'),
		)
	);
	$return['htmls']=$htmls;
	exi($return);
	
}
if($_RQ['op']=='step2'){
	$return['step']=2;
	$postdata=get_postdata();
	if($postdata['finalprice']<=0){
		exi('最终打款金额必须大于0','error');
	}
	$kuaiset=array(
		'ordermoney'=>$postdata['ordermoney'],
		'pingfee'=>$postdata['pingfee'],
		'dafee'=>$postdata['dafee'],
		'fuwufee'=>$postdata['fuwufee'],
		'jieprice'=>$postdata['jieprice'],
		'sys_choufee'=>$postdata['sys_choufee'],
	);
	$data=array(
		'clearno'=>get_ordersn('jy_merch_clearing','clearno'),
		'starttime'=>$postdata['starttime'],
		'endtime'=>$postdata['endtime'],
		'salsecount'=>$postdata['salsecount'],
		'ordermoney'=>$postdata['ordermoney'],
		'inpaycount'=>$postdata['inpaycount'],
		'inpaymoney'=>$postdata['inpaymoney'],
		'realprice'=>$postdata['realprice'],
		'price'=>$postdata['price'],
		'realpricerate'=>$postdata['realpricerate'],
		'finalprice'=>$postdata['finalprice'],
		'jifen'=>$postdata['jifen'],
		'pay_type'=>$postdata['pay_type'],
		'pay_trade_no'=>$postdata['pay_trade_no'],
		'realname'=>$postdata['realname'],
		'alipay'=>$postdata['alipay'],
		'bankname'=>$postdata['bankname'],
		'bankcard'=>$postdata['bankcard'],
		'content'=>$postdata['content'],
		'orderids'=>ijson_encode($postdata['orderids']),
		'kuaiset'=>ijson_encode($kuaiset),
		'status'=>0,
	);
	$data['uniacid']=$_SESSION['uniacid'];
	$data['merchid']=$merchid;
	$data['createtime']=time();
	pdo_insert('jy_merch_clearing',$data);
	$clearid=pdo_insertid();
	$params=array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'status'=>3,'clearstatus'=>0);
	if($postdata['orderids']){
		if($postdata['starttime'] || $postdata['endtime']){
			$params['createtime between']=array($postdata['starttime'],$postdata['endtime']);
		}
		$params['orderid']=$postdata['orderids'];
		pdo_update('jy_weishop_order_goods',array('clearstatus'=>1),$params);
		$params['id']=$postdata['orderids'];
		unset($params['orderid']);
		pdo_update('jy_weishop_order',array('clearstatus'=>1),$params);
	}
	$params=array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'status'=>1);
	if($this->session('balance_time')){
		if($postdata['starttime']){
			$params['createtime between']=array($postdata['starttime'],$postdata['endtime']);
		}else{
			$params['createtime <']=$this->session('balance_time');
		}
	}
	if($postdata['orderids']){
		$params['order_id']=$postdata['orderids'];
	}
	pdo_update('jy_merch_order',array('status'=>2,'clearid'=>$clearid),$params);
	$params=array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'status'=>1,'clearstatus'=>0);
	if($this->session('balance_time')){
		if($postdata['starttime']){
			$params['createtime between']=array($postdata['starttime'],$postdata['endtime']);
		}else{
			$params['createtime <']=$this->session('balance_time');
		}
	}
	pdo_update('jy_merch_paylog',array('clearstatus'=>1,'clearid'=>$clearid),$params);
	exi('创建结算单成功','','/tixian/');
}
if($_RQ['op']=='getapplyorder'){
	$pindex = max(1, intval($_RQ['page']));
	$psize = 10;
	$params=array('uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid);
    $fields=array();
    $orderby='id desc';
	$total='';
	$params=array('status'=>3,'uniacid'=>$_SESSION['uniacid'],'merchid'=>$merchid,'clearstatus'=>0);
	if($setting['balance_day']){
	//结算天数
		$time=TIMESTAMP-intval($setting['balance_day'])*86400;
		$params['finishtime <']=$time;
	}
	$return['list']=pdo_getslice('jy_weishop_order',$params,array($pindex,$psize),$total,$fields,'',$orderby);
	$totalpage=ceil($total/$psize);
	$totalpage=intval($totalpage);
	$return['totalpage'] =$totalpage;
	$return['params']['page'] =$pindex;
	foreach($return['list'] as &$item){
		$item['goods']=pdo_getall('jy_weishop_order_goods',array('orderid'=>$item['id'],'uniacid'=>$_SESSION['uniacid']),array('goodsid','optionid','price','total','goodssn','productsn'));
		foreach($item['goods'] as &$gv){
			$goodsinfo = pdo_get('jy_weishop_goods',array('id'=>$gv['goodsid'],'uniacid'=>$_SESSION['uniacid']),array('id','image','title','merchid'));
			$gv['title']=$goodsinfo['title'];
			$gv['weight']=pdo_getcolumn('jy_weishop_goods_dispatch',array('goodsid'=>$gv['goodsid']),'weight');
			//商品规格
			if($gv['optionid']){
				$specs=pdo_getcolumn('jy_weishop_goods_option',array('id'=>$gv['optionid']),'specs');
				$specs=explode("_",$specs);
				foreach($specs as &$spec){
					$spec=pdo_getcolumn('jy_weishop_goods_spec_item',array('id'=>$spec),'title');
				}
				$gv['selespename']=implode("，",$specs);
			}
		}
		$item['createtime']=date('Y/m/d H:i:s',$item['createtime']);
		$item['finishtime']=date('Y/m/d H:i:s',$item['finishtime']);
	}
	exi($return);
}